Ext.ns('app.crud.orm');

app.crud.orm.canEdit = false;
app.crud.orm.canDelete = false;

app.crud.orm.intTypes = ['tinyint','smallint','mediumint','int','bigint','bit'];
app.crud.orm.floatTypes = ['decimal' ,'float' ,'double'];

app.crud.orm.charTypes = ['char','varchar','bit'];
app.crud.orm.textTypes = ['tinytext','text','mediumtext','longtext'];
app.crud.orm.dateTypes = ['date','datetime','time','timestamp'];
app.crud.orm.blobTypes = ['tinyblob','blob','mediumblob','longblob'];
app.crud.orm.Actions = {};

Ext.define('app.crud.orm.ObjectsModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'title' ,  type:'string'},
        {name:'name' ,  type:'string'},
        {name:'table' , type:'string'},
        {name:'engine', type:'string'},	 	        
        {name:'vc', 	type:'boolean'},
        {name:'fields', type:'integer'},
        {name:'records',type:'integer'},
        {name:'data_size', type:'string'},
        {name:'index_size', type:'string'},
        {name:'validdb', typr:'boolean'},
        {name:'title', typr:'string'},
        {name:'save_history', type:'boolean'},
        {name:'link_title', type:'string'},
        {name:'rev_control',type:'boolean'}
    ]
});

Ext.define('app.crud.orm.Field', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'name' ,  type:'string'},
        {name:'title' , type:'string'},
        {name:'required', type:'boolean'},	 	        
        {name:'db_len', type:'integer'},
        {name:'db_isNull', type:'boolean'},
        {name:'db_default',type:'string'},
        {name:'is_search',type:'boolean'},
        {name:'system', type:'boolean'},
        {name:'type' , type:'string'},
        {name:'unique', type:'boolean'},
        {name:'link_type', type:'string'},
        {name:'object',type:'string'}
    ]
});


Ext.define('app.crud.orm.Index', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'name' ,  type:'string'},
        {name:'fulltext' , type:'boolean'},
        {name:'unique', type:'boolean'},	 	        
        {name:'columns', type:'string'},
        {name:'primary', type:'boolean'}
    ]
});

Ext.define('app.crud.orm.Main',{
	extend:'Ext.panel.Panel',
	dataStore:null,
	dataGrid:null,
	searchField:null,
	toolbarDataGrid:null,
	
	
	constructor: function(config) {	
		config = Ext.apply({
			layout:'fit',
			tbar:[]
	    }, config);		
		this.callParent(arguments);
   },
   
    initComponent:function(){
    	
    	this.dataStore = Ext.create('Ext.data.Store', {
		    model: 'app.crud.orm.ObjectsModel',
		    proxy: {
		        type: 'ajax',
		    	url:app.crud.orm.Actions.listObj,
		        reader: {
		            type: 'json',
		            root: 'data',
		            idProperty: 'name'
		        },
		        actionMethods : {
		    		create : 'POST',
		    		read   : 'POST',
		    		update : 'POST',
		    		destroy: 'POST'
		    	},
		        simpleSortMode: true
		    },
		    autoLoad: true,
		    sorters: [
		              {
		                  property : 'name',
		                  direction: 'ASC'
		              }
		    ]
		});
		
		if(app.crud.orm.canEdit){
			this.tbar = [{
				text:appLang.ADD_OBJECT,
				tooltip:appLang.ADD_OBJECT,
				listeners:{
					click:{
						fn:function(){
							this.showEdit('');
						},
						scope:this
					}
				}
			},{
				text:appLang.DICTIONARIES,
				tooltip:appLang.TOOLTIP_DICTIONARIES,
				listeners:{
					click:{
						fn:function(){
							this.showDictionary(false);
						},
						scope:this
					}
				}
			}];
		}

		this.searchField = new SearchPanel({store:this.dataStore,fieldNames:['name' , 'table']});

	   	this.toolbarDataGrid = Ext.create('Ext.toolbar.Toolbar', {
		   	items:[this.searchField,'-',{
	            xtype:'button',
	   	    	text:appLang.BUILD_ALL,
	   	    	tooltip:appLang.BUILD_ALL,
	   	    	icon:'/i/system/build.png',
	   	    	scope:this,
	   	    	handler:this.rebuildAllObjects
	   	    }]
	   	});
  	 
	   	if(app.crud.orm.canEdit) {
	   		this.toolbarDataGrid.add({
	   			text:appLang.MAKE_BACKUP,
	   			tooltip:appLang.MSG_MAKE_BACKUP_ALL,
	   			icon:'/i/system/database-export.png',
	   			scope:this,
	   			handler:this.makeBackUp
	   		});
	   		this.toolbarDataGrid.add({
	   			text:appLang.RESTORE_BACKUP,
	   			tooltip:appLang.RESTORE_BACKUP_TOOLTIP,
	   			icon:'/i/system/database-import.png',
	   			scope:this,
	   			handler:this.restoreBackUp
	   		});
	   	}
	   	var handle = this;
	   	this.dataGrid = Ext.create('Ext.grid.Panel',{
						store: this.dataStore,
						viewConfig: {
							stripeRows: true
						},
			            frame: false,
			            loadMask:true,
					    columnLines: true,
					    autoscroll:true,
					    bodyBorder:false,
						border:false,
					    tbar:this.toolbarDataGrid,
					    columns: [
					            {
					            	xtype:'actioncolumn',
					            	align:'center',
					            	width:60,
					            	items:[
					            	       {
					            	    	   tooltip:appLang.EDIT_RECORD,
					            	    	   icon:'/i/system/edit.png',
					            	    	   width:30,
					            	    	   iconCls:'buttonIcon',
					            	    	   handler:function(grid, rowIndex, colIndex){
					            	    		   handle.showEdit(grid.getStore().getAt(rowIndex).get('name'));
					            	    	   }
					            	       },{
					            	    	   tooltip:appLang.REBUILD_DB_TABLE,
					            	    	   icon:'/i/system/build.png',
					            	    	   width:30,
					            	    	   iconCls:'buttonIcon',
					            	    	   handler:function(grid, rowIndex, colIndex){
					            	    		   handle.rebuildObject(grid.getStore().getAt(rowIndex).get('name'));
					            	    	   }
					            	       }
					            	]
					            },{
					            	text:appLang.TITLE,
					            	width:200,
					            	dataIndex:'title',
					            	flex:1
					            },{
								    text: appLang.OBJECT,
								    dataIndex: 'name',
								    width:130,
								    align:'left'
								},{
									text:appLang.DATA_TABLE,
									dataIndex:'table',
									align:'left',
									width:170
					             },{
						            text: appLang.DB_ENGINE,
						            dataIndex: 'engine',
						            align:'center',
						            width:60
							      },{
								    text: appLang.PROPERTIES,
								    dataIndex: 'fields',
								    width:60,
								    align:'center'
								},
								{
									text:'Db Stats',
									columns:[
										{
										    text: appLang.RECORDS,
										    dataIndex: 'records',
										    width:60,
										    align:'center'
										},{
											text:appLang.DATA_SIZE,
											dataIndex:'data_size',
											width:70,
										    align:'center'
										},{
											text:appLang.INDEX_SIZE,
											dataIndex:'data_size',
											width:80,
										    align:'center'
										}
									]
								},
								{
								    sortable: true,
								    text: appLang.VC,
								    dataIndex: 'vc',
								    align:'center',
								    width:85,
								    renderer:app.checkboxRenderer
								},{
									text:appLang.VALID_DB,
									dataIndex: 'validdb',
								    align:'center',
								    width:50,
								    renderer:app.checkboxRenderer
								},{
									xtype:'actioncolumn',
					            	align:'center',
					            	width:30,
					            	scope:this,
					            	items:[{
			            	    		tooltip:appLang.DELETE_RECORD,
			            	    	   	icon:'/i/system/delete.gif',
			            	    	   	width:30,
			            	    	   	iconCls:'buttonIcon',
			            	    	   	handler:this.removeObject
									}]
								}
					    ],
					    listeners:{
					    	'itemdblclick':{
					    		fn:function(view , record , number , event , options){
					    			 this.showEdit(record.get('name'));
					    		},
					    		scope:this
					    	}
					    }
				});
	 this.items = [this.dataGrid];	 
	 this.callParent(arguments);
   },
   	removeObject:function(grid, rowIndex, colIndex){
   		var store = grid.getStore();
   		Ext.Msg.confirm(appLang.CONFIRM, appLang.MSG_OBJECT_REMOVE, function(btn){
   			if(btn != 'yes'){
   				return false;
   			}
   			
	   		Ext.getBody().mask(appLang.MSG_OBJECT_REMOVING);
			Ext.Ajax.request({
				url: app.crud.orm.Actions.removeObject,
			   	method: 'post',
			   	scope:this,
			   	params:{
			 		'objectName':store.getAt(rowIndex).get('name')
			 	},
			   	success: function(response, request) {
					response =  Ext.JSON.decode(response.responseText);
				   	if(response.success){
				   		store.removeAt(rowIndex);
				   	} else {
					   	Ext.Msg.alert(appLang.MESSAGE , response.msg);
				   	}
				   	Ext.getBody().unmask();
			   	},
			   	failure:function() {
				   	Ext.Msg.alert(appLang.MESSAGE , appLang.MSG_LOST_CONNECTION);
				   	Ext.getBody().unmask();
			   	}
		   });
   		}, this);
   	},
   restoreBackUp:function(){
	   var win = Ext.create('app.crud.orm.restoreBackupWindow',{});
	   win.on('backupRestored',function(){
		   this.dataStore.load();
	   },this);
	   win.show();
   },
   makeBackUp:function(){
	   Ext.getBody().mask(appLang.MSG_BACKUP_PROCESSING);
	   Ext.Ajax.request({
		   url: app.crud.orm.Actions.makeBackUp,
		   method: 'post',
		   scope:this,
		   success: function(response, request) {
			   response =  Ext.JSON.decode(response.responseText);
			   if(!response.success){
				   Ext.Msg.alert(appLang.MESSAGE , response.msg);
			   }
			   Ext.getBody().unmask();
		   },
		   failure:function() {
			   Ext.Msg.alert(appLang.MESSAGE , appLang.MSG_LOST_CONNECTION);
			   Ext.getBody().unmask();
		   }
	   });
   },
   rebuildAllObjects:function(){
	   Ext.Msg.confirm(appLang.CONFIRMATION, appLang.MSG_CONFIRM_REBUILD, function(btn){
		   if(btn != 'yes')
			   return;
		   
		   var handle = this;
		   var oNamesList = [];
		   this.dataStore.each(function(record){
			   oNamesList.push(record.get('name'));
		   },this);
		   
		   Ext.Ajax.request({
		 		url: app.crud.orm.Actions.buildAllObjects,
		 		method: 'post',
		 		params:{
		 			'names[]':oNamesList
		 		},
		         success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				handle.dataStore.load();
		 			}else{
		 				Ext.Msg.alert(appLang.MESSAGE , response.msg);
		 			}
		       },
		       failure:function() {
		    	   Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		       }
		   });
	   }, this);
   },
   showEdit:function(name , title){
	 var oList = [];
	 this.dataStore.each(function(record){
		 var title = record.get('title');
		 if(title.length)
			 title=' ('+title+')';
		 
		 oList.push({id:record.get('name'),title:(record.get('name')+title)});
	 },this);
	   
	 var win = Ext.create('app.crud.orm.ObjectWindow',{
		 objectName:name,
		 objectList:oList
	 }); 
	 win.setTitle(appLang.EDIT_OBJECT + ' &laquo;' + name + '&raquo; ');
	 win.on('dataSaved',function(){
		this.dataStore.load();
	 },this);
	 win.on('showdictionarywin',function(name){
	 	this.showDictionary(name);
	 },this);
	 win.show();
   },
   showDictionary:function(name){
		Ext.create('app.crud.orm.DictionaryWindow', {
			curDictionary:name,
			controllerUrl:app.crud.orm.Actions.dictionary,
			canEdit:app.crud.orm.canEdit,
			canDelete:app.crud.orm.canDelete
		}).show();  
   },
   rebuildObject:function(name){
	   var handle = this;
	   this.win = Ext.create('Ext.Window',{
		 width:400,
		 height:500,
		 modal:true,
		 autoScroll:true,
		 layout:'fit',
		 title:appLang.REBUILD_INFO,
		 closeAction:'destroy',
		 buttons:[
		      {
		    	  text:appLang.CANCEL,
		    	  scope:handle,
		    	  handler:function(){
		    		  this.win.close();
		    	  }
		      },{
		    	  text:appLang.APPLY,
		    	  scope:handle,
		    	  handler:function(){
		    		  this.buildObject(name);
		    		  this.win.close();
		    	  }
		      }   
		 ]
	   });
	   this.win.show();
	   this.win.setLoading(appLang.FETCHING_INFO);
	   
	   Ext.Ajax.request({
	 		url: app.crud.orm.Actions.validateObject,
	 		method: 'post',
	 		params:{
	 			'name':name
	 		},
	         success: function(response, request) {
	 			response =  Ext.JSON.decode(response.responseText);
	 			if(response.success){
	 				if(response.nothingToDo){
	 					Ext.Msg.alert(appLang.MESSAGE, appLang.NTD);
	 					handle.win.close();
	 				}else{
	 					handle.win.add({
		 					xtype:'panel',
		 					autoScroll:true,
		 					html:response.text,
		 					bodyPadding:3		 					
		 				});
	 				}
	 			}else{
	 				Ext.Msg.alert(appLang.MESSAGE , appLang.CANT_GET_VALIDATE_INFO);
	 			}	
	 			handle.win.setLoading(false);
	       },
	       failure:function() {
	       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
	       	handle.win.setLoading(false);
	       }
	   });
   },
   buildObject:function(name){
	   var handle = this;
	   Ext.Ajax.request({
	 		url: app.crud.orm.Actions.buildObject,
	 		method: 'post',
	 		params:{
	 			'name':name
	 		},
	         success: function(response, request) {
	 			response =  Ext.JSON.decode(response.responseText);
	 			if(response.success){
	 				handle.dataStore.load();
	 			}else{
	 				Ext.Msg.alert('Error' , response.msg);
	 			}	
	       },
	       failure:app.formFailure 
	 	});
   }
});

Ext.onReady(function(){
	
	app.crud.orm.Actions = {
			addDictionary:		app.root + 'adddictionary',
			listDictionaries:	app.root + 'listdictionaries',
			updateDictionary:	app.root + 'updatedictionary',
			removeDictionary:	app.root + 'removedictionary',
			listObj: 			app.root + 'list',
			listObjFields: 		app.root + 'fields',
			listObjIndexes: 	app.root + 'indexes',
			listBackups: 		app.root + 'listbackups',
			loadObjCfg: 		app.root + 'load',
			loadObjField: 		app.root + 'loadfield',
			loadObjIndex: 		app.root + 'loadindex',
			makeBackUp: 		app.root + 'makebackup',
			removeBackUp:		app.root + 'removebackup',
			removeObject:		app.root + 'removeobject',
			restoreBackup: 		app.root + 'restorebackup',
			saveObjCfg: 		app.root + 'save',
			saveObjField: 		app.root + 'savefield',
			saveObjIndex:	 	app.root + 'saveindex',
			deleteIndex: 		app.root + 'deleteindex',
			deleteField:	 	app.root + 'deletefield',
			validateObject: 	app.root + 'validate',
			buildObject:		app.root + 'build',
			buildAllObjects:	app.root + 'buildall',
			dictionary:			app.createUrl([app.root+'dictionary',''])
	};

	app.crud.orm.canEdit = canEdit;
	app.crud.orm.canDelete = canDelete;
	app.crud.orm.canUserBackup = canUserBackup;
	
	var dataPanel = Ext.create('app.crud.orm.Main',{
		title:appLang.MODULE_ORM
	});
	
	app.content.add(dataPanel);
});

